using System;
using Agatha.Common;
using Source.Common;

namespace Source.ServiceLayer
{
    public interface IAuthenticationManager : IDisposable
    {
        Visit Authenticate(string username);
        Visit Authenticate(string username, string password);
        bool IsAuthenticated(Visit visit);
    }

    public class AuthenticationManager : Disposable, IAuthenticationManager
    {
        private readonly IOlaMembershipProvider membershipProvider;
        private readonly ISessionTokenCache sessionTokenCache;
        private readonly ITokenProvider tokenProvider;

        public AuthenticationManager(IOlaMembershipProvider membershipProvider, ISessionTokenCache sessionTokenCache, 
            ITokenProvider tokenProvider)
        {
            this.membershipProvider = membershipProvider;
            this.sessionTokenCache = sessionTokenCache;
            this.tokenProvider = tokenProvider;
        }

        public Visit Authenticate(string username)
        {
            Guid token = tokenProvider.GenerateToken();
            var user = GetUserInfo(username);

            if (user == null)
            {
                return null;
            }

            sessionTokenCache.StoreWithDefaultTimeOut(token, user);

            return new Visit(token, user, username);
        }

        public Visit Authenticate(string username, string password)
        {
            if (!membershipProvider.ValidateUser(username, password))
            {
                return null;
            }

            return Authenticate(username);
        }

        public bool IsAuthenticated(Visit visit)
        {
            return true;
            if (visit == null)
            {
                return false;
            }

            return sessionTokenCache.IsTokenForUserCorrect(visit.Token, visit.User);
        }

        private IUser GetUserInfo(string username)
        {
            var alcatelLucentUser = membershipProvider.GetUser(username);
            return new UserDto();
           // return ((GetUserResponse) getUserRequestHandler.Handle(new GetUserRequest { EmailAddress = alcatelLucentUser.Email, Upi = alcatelLucentUser.UniqueIdentifier })).User;
        }

        protected override void DisposeManagedResources()
        {
            //if (getUserRequestHandler != null)
            //{
            //    getUserRequestHandler.Dispose();
            //}
        }
    }
}
